package com.canbot.u05.activity.customvoice

import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Environment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.MainApplication
import com.canbot.u05.R
import com.canbot.u05.activity.*
import com.canbot.u05.activity.customvoice.adapter.CustomDialogMainAdapter
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelData
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas
import com.canbot.u05.activity.customvoice.tool.CommonDialog
import com.canbot.u05.activity.customvoice.tool.CustomDialogView
import com.canbot.u05.activity.customvoice.tool.ExportExcelUtils
import com.canbot.u05.bean.CustomDialogue
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.*
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_custom_dialog_main.*
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 * CustomDialogMainActivity
 *
 * @author  Liu.Heng
 * @date  2019/5/29
 */
class CustomDialogMainActivity : BaseActivityNoTitle() {

    private lateinit var customDialogMainAdapter: CustomDialogMainAdapter

    private lateinit var mList: MutableList<CustomDialogExcelDatas>

    private lateinit var mDelList: MutableList<CustomDialogExcelDatas>

    private lateinit var dialogLoading: Dialog

    private lateinit var questionList: MutableList<String>


    private var handler = getHandler {
        getDialogs()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_custom_dialog_main)
        initView()
    }


    fun initView() {
        mList = ArrayList()
        mDelList = ArrayList()
        questionList = ArrayList()
        my_recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        customDialogMainAdapter = CustomDialogMainAdapter(this, mList, object : CustomDialogMainAdapter.Callback {
            override fun clickEvent(v: View, type: Int) {
                when (type) {
                    /**勾选按钮添加*/
                    1 -> {
                        loge("勾选了")
                        mDelList.add(mList[v.tag as Int])
                        if (mDelList.size == mList.size) {
                            choose_all_btn.text = "取消全选"
                        }
                    }
                    /**勾选按钮取消*/
                    2 -> {
                        loge("取消勾选了")
                        choose_all_btn.text = "全选"
                        mDelList.remove(mList[v.tag as Int])
                    }
                    /**对话详情*/
                    3 -> {
                        reset()
                        val intent = Intent(this@CustomDialogMainActivity, CustomDialogDetailsActivity::class.java)
                        intent.putExtra("data", JSON.toJSONString(mList[v.tag as Int]))
                        intent.putExtra("questions", JSON.toJSONString(questionList))
                        startActivity(intent)
                    }
                    else -> {
                    }
                }
            }
        })
        my_recyclerView.adapter = customDialogMainAdapter

        my_back.setOnClickListener(::onClick)
        add_dialog.setOnClickListener(::onClick)
        my_editText.setOnClickListener(::onClick)
        choose_all_btn.setOnClickListener(::onClick)
        delete_btn.setOnClickListener(::onClick)
        my_exPort.setOnClickListener(::onClick)
        my_imPort.setOnClickListener(::onClick)
    }

    private fun onClick(view: View) {
        when (view.id) {
            /**添加问答*/
            R.id.add_dialog -> {
                reset()
                val intent = Intent(this, CustomDialogAddQuestionActivity::class.java)
                intent.putExtra("data", JSON.toJSONString(CustomDialogExcelDatas()))
                intent.putExtra("questions", JSON.toJSONString(questionList))
                startActivity(intent)
                overridePendingTransitionExt()
            }
            /**编辑*/
            R.id.my_editText -> {
                if (my_editText.text.contains("取消")) {
                    my_editText.text = ""
                    my_editText.background = ContextCompat.getDrawable(this, R.drawable.custom_dialog2_edit)
                    customDialogMainAdapter.setEdit(false)
                    /** 通过构造器 并且 传递 需要移动的参数*/
                    val objectAnimator = ObjectAnimator.ofFloat(delete_relativeLayout, "translationY", 0F)
                    objectAnimator.duration = 0
                    objectAnimator.start()
                } else {
                    my_editText.text = "取消"
                    my_editText.background = ColorDrawable(Color.TRANSPARENT)
                    customDialogMainAdapter.setEdit(true)
                    /** 通过构造器 并且 传递 需要移动的参数*/
                    val objectAnimator = ObjectAnimator.ofFloat(delete_relativeLayout, "translationY", -delete_relativeLayout.measuredHeight.toFloat())
                    objectAnimator.duration = 0
                    objectAnimator.start()
                }
            }
            /**全选*/
            R.id.choose_all_btn -> {
                if (choose_all_btn.text.contains("取消全选")) {
                    mDelList.clear()
                    customDialogMainAdapter.notifyChooseAll(false)
                    choose_all_btn.text = "全选"
                } else {
                    mDelList.clear()
                    mDelList.addAll(mList)
                    customDialogMainAdapter.notifyChooseAll(true)
                    choose_all_btn.text = "取消全选"
                }
            }
            /**删除*/
            R.id.delete_btn -> {
                delDialogs()
            }
            /**返回*/
            R.id.my_back -> {
                finish()
                overridePendingTransitionExt()
            }
            /**导出*/
            R.id.my_exPort -> {
                if (mList.isEmpty()) {
                    showToast("数据为空!")
                    return
                }
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this@CustomDialogMainActivity, getString(R.string.loading))
                dialogLoading.show()
                exportExcelData()
            }
            /**导入*/
            R.id.my_imPort -> {
                reset()
                val intent = Intent(this, CustomDialogActivity::class.java)
                intent.putExtra("data", JSON.toJSONString(questionList))
                startActivity(intent)
                overridePendingTransitionExt()
            }
            else -> {
            }
        }

    }


    override fun onResume() {
        super.onResume()
        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzdh_001.wav")
        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "30")
        handler.sendEmptyMessageDelayed(0, 500)
    }

    private fun getDialogs() {
        mList.clear()
        mDelList.clear()
        questionList.clear()
//        for (i in (application as MainApplication).mCustomDialogues.indices) {
//            questionList.add((application as MainApplication).mCustomDialogues[i].question)
//        }
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@CustomDialogMainActivity, getString(R.string.loading))
        dialogLoading.show()
        val url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "dialogcustom"
        val hashMap = HashMap<String, String>()
        hashMap["type"] = "5"
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                runOnUiThread {
                    val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                    if (strMsgBean.rc == 0) {
                        loge("strMsgBean=$strMsgBean")
                        val customDialogExcelDataList = JSON.parseArray(strMsgBean.result.toString(), CustomDialogExcelDatas::class.java)
                        mList.addAll(customDialogExcelDataList)
                        if (mList.isEmpty()) {
                            if (my_editText.text.contains("取消")) {
                                my_editText.text = null
                                my_editText.background = ContextCompat.getDrawable(this@CustomDialogMainActivity, R.drawable.custom_dialog2_edit)
                                customDialogMainAdapter.setEdit(false)
                                /** 通过构造器 并且 传递 需要移动的参数*/
                                val objectAnimator = ObjectAnimator.ofFloat(delete_relativeLayout, "translationY", 0F)
                                objectAnimator.duration = 0
                                objectAnimator.start()
                            }
                            my_editText.isEnabled = false
                        } else {
                            my_editText.isEnabled = true
                            mList.sortWith(Comparator { t2, t1 ->
                                t1.listQsBean.first().cmd_id.compareTo(t2.listQsBean.first().cmd_id)
                            })
                            mList.forEach {

                                it.listQsBean.forEach { questionBean ->
                                    questionList.add(questionBean.question)
                                }
                            }
                        }
                        customDialogMainAdapter.notify(mList)
                        showToast("加载成功")
                    }
                    dialogLoading.dismiss()
                }
            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    showToast(getString(R.string.network_error))
                }
            }
        })

    }

    /**
     * 跳转页面时,编辑按钮恢复最初状态
     */
    private fun reset() {
        mDelList.clear()
        customDialogMainAdapter.notifyChooseAll(false)
        choose_all_btn.text = "全选"
        my_editText.text = ""
        my_editText.background = ContextCompat.getDrawable(this, R.drawable.custom_dialog2_edit)
        customDialogMainAdapter.setEdit(false)
        /** 通过构造器 并且 传递 需要移动的参数*/
        val objectAnimator = ObjectAnimator.ofFloat(delete_relativeLayout, "translationY", 0F)
        objectAnimator.duration = 0
        objectAnimator.start()
    }

    private fun delDialogs() {
        if (mDelList.isEmpty()) {
            showToast("请先勾选出您想要删除的对话")
            return
        }

        loge("mDelList=$mDelList")

        CustomDialogView(this, object : CustomDialogView.OnCloseListener {
            override fun onClick(dialog: Dialog?, confirm: Boolean) {
                if (confirm) {
                    dialog?.dismiss()
                    dialogLoading = LoadingDialogUtils.createLoadingDialog(this@CustomDialogMainActivity, "正在删除中...")
                    dialogLoading.show()
                    val url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "dialogcustom"
                    val hashMap = HashMap<String, String>()
                    hashMap["type"] = "1"
                    hashMap["delDialogs"] = JSON.toJSONString(mDelList)
                    OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
                        override fun onSuccess(result: String) {
                            dialogLoading.dismiss()
                            loge("result$result")
                            val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                            if (strMsgBean.rc == 0) {
                                runOnUiThread {

                                    showToast(getString(R.string.deleted_successfully))
                                    choose_all_btn.text = "全选"
                                    handler.sendEmptyMessage(0)
                                }
                            } else {
                                showToast(getString(R.string.delete_failed))
                            }
                        }

                        override fun onFailure() {
                            runOnUiThread {
                                dialogLoading.dismiss()
                                showToast(getString(R.string.delete_failed))
                            }
                        }
                    })
                }
            }
        }, "提示", "是否删除这${mDelList.size}条对话").show()
    }

    private fun exportExcelData() {
        runOnUiThread {
            val customDialogExcelDatas: MutableList<CustomDialogExcelData> = ArrayList()
            val exportData: MutableList<CustomDialogExcelDatas> = ArrayList(mList)
            for (i in exportData.indices) {
                val questionBeanList = exportData[i].listQsBean
                val answerBeanList = exportData[i].listAsBean

                if (questionBeanList.size >= answerBeanList.size) {
                    questionBeanList.indices.forEach {
                        val data = CustomDialogExcelData()
                        data.question_str = questionBeanList[it].question
                        data.tts_text = if (answerBeanList.size > it) if (answerBeanList[it].type == 1) answerBeanList[it].ttstext else answerBeanList[it].soundpath.replace("/uusound/", "") else ""
                        data.image_path = if (answerBeanList.size > it) if (answerBeanList[it].imgpath.isEmpty()) "" else answerBeanList[it].imgpath.replace("/uupic/", "") else ""
                        customDialogExcelDatas.add(data)
                        if (it == questionBeanList.size - 1) {
                            val nullData = CustomDialogExcelData()
                            nullData.question_str = ""
                            nullData.tts_text = ""
                            nullData.image_path = ""
                            customDialogExcelDatas.add(nullData)
                        }
                    }
                } else {
                    answerBeanList.indices.forEach {
                        val data = CustomDialogExcelData()
                        data.question_str = if (questionBeanList.size > it) questionBeanList[it].question else ""
                        data.tts_text = if (answerBeanList[it].type == 1) answerBeanList[it].ttstext else answerBeanList[it].soundpath.replace("/uusound/", "")
                        data.image_path = if (answerBeanList[it].imgpath.isEmpty()) "" else answerBeanList[it].imgpath.replace("/uupic/", "")
                        customDialogExcelDatas.add(data)
                        if (it == answerBeanList.size - 1) {
                            val nullData = CustomDialogExcelData()
                            nullData.question_str = ""
                            nullData.tts_text = ""
                            nullData.image_path = ""
                            customDialogExcelDatas.add(nullData)
                        }
                    }
                }
            }
            if (customDialogExcelDatas.isEmpty()) {
                showToast("数据为空!")
            } else {
                loge("数据导出=${customDialogExcelDatas.size}")
                loge("数据导出=${customDialogExcelDatas[0]}")
                var filePath = Environment.getExternalStorageDirectory().toString() + File.separator
                val file = filePath.file()
                if (!file.exists()) {
                    file.mkdirs()
                }
                val excelFileName = "/QA-Export.xls"
                val title = arrayOf("问题", "答案", "图片")
                filePath = "$filePath$excelFileName"
                ExportExcelUtils.initExcel(filePath, title)
                ExportExcelUtils.writeObjListToExcel(customDialogExcelDatas, filePath)
                dialogLoading.dismiss()
                CommonDialog(this, R.style.dialog, "导出成功,平板SD卡下的QA-Export.xls为导出文件!", true, getString(R.string.sure),
                        object : CommonDialog.OnCloseListener {
                            override fun onClick(dialog: Dialog, confirm: Boolean) {
                                dialog.dismiss()
                            }
                        }).setTitle("提示").show()
            }
        }
    }

}
